﻿using System;
using System.Globalization;
using System.Security.Principal;
using System.Threading;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using DevFramework.Core.CrossCuttingConcern.Security.Web;
using DevFramework.Business.Concrete.Managers;
using DevFramework.Business.DependencyResolvers.Ninject;
using DevFramework.MvcUI.Infrastructure;
using DevFramework.MvcUI.ModelBinders;
using FluentValidation.Mvc;

namespace DevFramework.MvcUI
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RouteConfig.RegisterRoutes(RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

            //Bir action parametrelerinde Cart istiyorsa, Cart Model binder map edilir.
            System.Web.Mvc.ModelBinders.Binders.Add(typeof (CartManager), new CartModelBinder());

            ModelValidatorProviders.Providers.Clear();

            FluentValidationModelValidatorProvider.Configure(provider =>
            {
                provider.ValidatorFactory = new NinjectValidatoryFactory();
                provider.AddImplicitRequiredValidator = false;
            });
        }

        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            try
            {
                var prin = new GenericPrincipal(new MyIdentity
                {
                    SessionId = Session.SessionID,
                    Url = Request.RawUrl,

                }, new string[] { });
                Thread.CurrentPrincipal = prin;
            }
            catch (Exception)
            {
            }

            string culture = "tr-TR";

            if (Request.Cookies["culture"] != null && !string.IsNullOrEmpty(Request.Cookies["culture"].Value))
            {
                culture = Request.Cookies["culture"].Value;
            }
            else
            {
                if (Request.UserLanguages != null) culture = Request.UserLanguages[0];
            }

            var ci = new CultureInfo(culture);

            Thread.CurrentThread.CurrentUICulture = ci;
            Thread.CurrentThread.CurrentCulture = ci;
        }

        //void Application_Error(object sender, EventArgs e)
        //{
        //    Exception exc = Server.GetLastError();

        //    var logger = new EventLoggerService();

        //    logger.Info(exc.Message);
        //    //if (exc.GetType() == typeof(InvalidOperationException))
        //    //{
        //    //    if (exc.Message.Contains("IControllerFactory"))
        //    //        Response.RedirectToRoute(new {controller = "Error", action = "NoPageFound"});
        //    //}

        //    Server.ClearError();
        //}
    }
}
